package com.example.smartvillage.cunwei;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.format.Time;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.example.smartvillage.R;
import com.example.smartvillage.utils.TimeFormatter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InformationListActivity extends AppCompatActivity {

    int REQUEST_CODE_SCAN = 111;

    FloatingActionButton fab_scan_code;
    ListView listView;

    ActivityResultLauncher<String> requestCameraPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (isGranted) {
                    Intent intent = new Intent(InformationListActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                } else {
                    new AlertDialog.Builder(this)
                            .setTitle("缺少相机权限")
                            .setMessage("需要相机权限以使用扫码功能")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            })
                            .show();
                }
            });

    String[] name = {"张三", "李四"};
    String[] age = {"30", "40"};
    String[] time = {"2021-04-22 22:25:34", "2021-04-22 22:26:54"};
    List<Map<String,String>> mData= new ArrayList<>();
    SimpleAdapter simpleAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_information_list);

        for(int i = 0; i < name.length; i++) {
            Map<String,String> item = new HashMap<>();
            item.put("name", name[i]);
            item.put("age", age[i]);
            item.put("time", time[i]);

            mData.add(item);
        }

        simpleAdapter = new SimpleAdapter(
                this
                ,mData
                , R.layout.item_cunmin_info
                , new String[]{"name","age","time"}
                , new int[]{R.id.cummin_info_name,R.id.cummin_info_age,R.id.cummin_info_time});

        fab_scan_code = findViewById(R.id.info_list_scan_code);
        listView = findViewById(R.id.info_list_list);
        listView.setAdapter(simpleAdapter);

        fab_scan_code.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(InformationListActivity.this, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SCAN);
            }
            else {
                requestCameraPermissionLauncher.launch(Manifest.permission.CAMERA);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                JsonElement jsonElement = JsonParser.parseString(content);
                if (jsonElement.isJsonObject()) {
                    JsonObject jsonObject = jsonElement.getAsJsonObject();
                    if (jsonObject.has("cunmin_name") && jsonObject.has("cunmin_age")
                            && jsonObject.has("cunmin_time")) {
                        Map<String,String> item = new HashMap<>();
                        item.put("name", jsonObject.get("cunmin_name").getAsString());
                        item.put("age", jsonObject.get("cunmin_age").getAsString());
                        item.put("time", TimeFormatter.getDate(jsonObject.get("cunmin_time").getAsLong()));
                        mData.add(item);
                        simpleAdapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }
}